package cn.darkhorse.ticket.code;

import cn.darkhorse.exception.ServiceException;
import cn.darkhorse.ticket.constants.TicketConstants;
import cn.darkhorse.ticket.service.IRepeatCheckService;
import cn.darkhorse.workflow.tool.BusinessConstants;
import com.baomidou.mybatisplus.extension.service.IService;
import com.ruoyi.common.utils.StringUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.lang.reflect.Field;

/**
 * @description:
 * @author: mr.wang
 * @time: 2024/1/12 10:59
 */
@Component
public class RepeatCheck<T> {
	
	@Resource
	IRepeatCheckService<T> repeatCheckService;
	
	public String repeat(IService iService,T t,String bussinesType) {
		String code = null;
		String id = fieldValue(t, TicketConstants.FIELD_ID);
		String codeOriginal = fieldValue(t, TicketConstants.FIELD_CODE);
		String name = fieldValue(t, TicketConstants.FIELD_NAME);
		String isAutomatically = fieldValue(t, TicketConstants.FIELD_AUTOMATICALLY);
		boolean b = StringUtils.isBlank(id) || "null".equals(id);
		if(b){
			code = repeatCheckService.repeatAutoCodeAndName(iService, null, bussinesType,
					codeOriginal, name,Boolean.valueOf(isAutomatically));
		}else {
			repeatCheckService.repeatName(iService, Long.valueOf(id),name);
		}
		return code;
	}
	
	/**
	 * 自动生成，校验编码
	 * @param iService
	 * @param t
	 * @param bussinesType
	 * @return
	 */
	public String repeatCode(IService iService,T t,String bussinesType) {
		String codeOriginal = fieldValue(t, TicketConstants.FIELD_CODE);
		String isAutomatically = fieldValue(t, TicketConstants.FIELD_AUTOMATICALLY);
		String code = repeatCheckService.repeatAutoCode(iService, null, bussinesType,
					codeOriginal,Boolean.valueOf(isAutomatically));
		return code;
	}
	
	
	
	private String fieldValue(T t, String field){
		String value;
		try {
			//获取  无字段封掉
			Field codeField = t.getClass().getDeclaredField(BusinessConstants.toCamelCase(field));
			codeField.setAccessible(true);
			try {
				//获取字段 无字段封掉
				value = String.valueOf(codeField.get(t));
			} catch (IllegalAccessException e) {
				e.printStackTrace();
				throw new ServiceException(e.getMessage());
			}
		} catch (NoSuchFieldException e) {
			try {
				Field codeField = t.getClass().getSuperclass().getDeclaredField(BusinessConstants.toCamelCase(field));
				codeField.setAccessible(true);
				try {
					//获取字段 无字段封掉
					value = String.valueOf(codeField.get(t));
				} catch (IllegalAccessException d) {
					d.printStackTrace();
					throw new ServiceException(d.getMessage());
				}
			} catch (NoSuchFieldException e1) {
				e1.printStackTrace();
				throw new ServiceException(e1.getMessage());
			}
		}
		return value;
	}
	
	
	
}
